﻿using LPBToolsLib;
using LPBToolsLib.NetSocket;
using PLCConsole;
using StationNF;
using StationSer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DExSerConsoleV1
{
    public partial class FDexSerConsoleNF : Form
    {
        public static DExSerConsoleCFG DUServerCFG { get; set; }
        public StationsServer StationsSer { get; set; }
        public UDPPassiveBus tUDPSer { get; private set; } = null;
        public JCommandServer tJCommandSer { get; private set; } = null;
        public Dictionary<string, byte[]> tClientsDatas { get; } = new Dictionary<string, byte[]>();
        public FDexSerConsoleNF()
        {
            InitializeComponent();
            string sDir = System.Environment.CurrentDirectory;
            DUServerCFG = new DExSerConsoleCFG(new JSONINISettings(sDir + "\\" + "DExUDPServer.ini"));
            if ((DUServerCFG.DExSerUDPPort >= numericUpDownServerPort.Minimum)
                    && (DUServerCFG.DExSerUDPPort <= numericUpDownServerPort.Maximum))
                numericUpDownServerPort.Value = DUServerCFG.DExSerUDPPort;
            if ((DUServerCFG.CommandSerPort >= numericUpDownAPISerPort.Minimum)
                    && (DUServerCFG.CommandSerPort <= numericUpDownAPISerPort.Maximum))
                numericUpDownAPISerPort.Value = DUServerCFG.CommandSerPort;

            IPAddress[] tSerIPList = TCPServerSocket.getIpAddressList();
            foreach (IPAddress tSerIP in tSerIPList)
                comboBoxIPList.Items.Add(tSerIP.ToString());

            IPAddress tCFGIP = IPAddress.Any;

            tCFGIP = IPAddress.Parse(DUServerCFG.DExSerSerIP);
            if (comboBoxIPList.Items.Count > 0)
                for (int i = 0; i < comboBoxIPList.Items.Count; i++)
                    if (comboBoxIPList.Items[i].ToString().Equals(tCFGIP.ToString()))
                    {
                        comboBoxIPList.SelectedIndex = i;
                        break;
                    }
        }

        private void tDeamon_Tick(object sender, EventArgs e)
        {
            if (tUDPSer!=null)
            {
                buttonSerStarStop.Text = "StopServer";
                groupBoxDExSer.Enabled = false;
                listViewStaList.Visible = true;
                List<string> tOnlineStaIDList = new List<string>(StationsSer.StationsIDList);

                if ((listViewStaList.Items.Count != tOnlineStaIDList.Count) || (listViewStaList.Items.Count == 0))
                {
                    listViewStaList.Items.Clear();
                    foreach (string StaID in tOnlineStaIDList)
                    {
                        ListViewItem tItem = new ListViewItem(StaID);
                        tItem.SubItems.Add("");
                        tItem.SubItems.Add("");
                        tItem.SubItems.Add("");
                        listViewStaList.Items.Add(tItem);
                    }
                }
                if ((listViewStaList.Items.Count == tOnlineStaIDList.Count) && (tOnlineStaIDList.Count > 0))
                {
                    for (int i = 0; i < tOnlineStaIDList.Count; i++)
                    {
                        IFDExCommunicater tDExCommunicater = StationsSer.getCommunicater(tOnlineStaIDList[i]);
                        if (tDExCommunicater != null)
                        {
                            IFStation tPLCStation = tDExCommunicater.Station;
                            listViewStaList.Items[i].Text = tDExCommunicater.StationID;
                            listViewStaList.Items[i].SubItems[1].Text = tDExCommunicater.LastPacketTime.ToString("HH:mm:ss.fff");
                            if (tPLCStation != null)
                            {
                                string sPLCInfo = "";
                                if ((tPLCStation.StationType>0) &&(Enum.IsDefined(typeof(StationPLCType), tPLCStation.StationType)))
                                {
                                    sPLCInfo = ((StationPLCType)tPLCStation.StationType).ToString()+":";
                                }
                                sPLCInfo += string.Format("{0}:{1}[{2}]",
                                        tPLCStation.StationRegStar,
                                    tPLCStation.StationRegCount,
                                    tDExCommunicater.SourEndPoint.ToString());
                                listViewStaList.Items[i].SubItems[2].Text = sPLCInfo;
                            }
                            listViewStaList.Items[i].Tag = tDExCommunicater;
                        }
                    }
                }
            }
            else
            {
                buttonSerStarStop.Text = "StarServer";
                groupBoxDExSer.Enabled = true;
                listViewStaList.Visible = false;
            }
        }

        private void buttonSerStarStop_Click(object sender, EventArgs e)
        {
            if (tUDPSer != null)
            {
                tUDPSer.CloseAll();
                tUDPSer = null;
                if (StationsSer != null)
                {
                    StationsSer.CloseAll();
                    StationsSer = null;
                }
                if (tJCommandSer != null)
                {
                    tJCommandSer.CloseAll();
                    tJCommandSer=null;
                }
            }
            else
            {
                IPAddress tSerIP = IPAddress.Any;
                if (comboBoxIPList.SelectedIndex>=0)
                {
                    tSerIP=IPAddress.Parse(comboBoxIPList.SelectedItem.ToString());
                }
                tUDPSer = new UDPPassiveBus(new IPEndPoint(tSerIP, (int)numericUpDownServerPort.Value));
                StationsSer = new StationsServer();
                if (StationsServer.ServerIF!=null)
                {

                }
                StationsSer.CommandTOutMs = (int)numericUpDownTimeOut.Value;
                tUDPSer.OnRecPacket += StationsSer.doRecDatas;
                tJCommandSer = new JCommandServer(StationsSer);
                tJCommandSer.StarListen(new IPEndPoint(IPAddress.Any, (int)numericUpDownAPISerPort.Value));
            }
        }

        private void FDexSerConsoleNF_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (tUDPSer != null)
            {
                tUDPSer.CloseAll();
                tUDPSer = null;
                if (StationsSer != null)
                    StationsSer.CloseAll();
                if (tJCommandSer != null)
                {
                    tJCommandSer.CloseAll();
                    tJCommandSer = null;
                }
            }
        }

        private void numericUpDownTimeOut_ValueChanged(object sender, EventArgs e)
        {
            if(StationsSer!=null)
            {
                StationsSer.CommandTOutMs = (int)numericUpDownTimeOut.Value;
            }
        }

        private void ToolStripMenuItem打开PLC面板_Click(object sender, EventArgs e)
        {
            if (listViewStaList.SelectedItems.Count >= 1)
            {
                string StaID = listViewStaList.SelectedItems[0].Text;
                //IFDExCommunicater tDExCommunicater=(IFDExCommunicater)listViewStaList.SelectedItems[0].Tag;
                if (!string.IsNullOrEmpty(StaID))
                {
                    FOpenPLCConsole tOpenPLCConsole = new FOpenPLCConsole(StationsSer, StaID);
                    tOpenPLCConsole.ShowDialog();
                }
            }
        }
    }

}
